<template>
  <div class="cart">
    <van-sticky>
      <nav-bar style="background: var(--theme-color); color: white">
        <span slot="center">购物车</span>
        <span slot="right" style="font-size: 12px" @click="isEdit = !isEdit"
          >编辑</span
        >
      </nav-bar>
    </van-sticky>
    <div style="height: 120px; background: var(--theme-color)"></div>
    <div class="cart-body" v-if="carts.length > 0">
      <van-checkbox-group v-model="ids">
        <template v-for="(item, index) in carts">
          <!-- 点击事件是点击购物车商品跳转到商品详情 -->
          <div class="cart-item" :key="item.id">
            <div style="width: 20px; margin-right: 10px">
              <van-checkbox
                icon-size="14px"
                checked-color="#ff7500"
                :name="item.id"
              />
            </div>
            <div
              @click="
                $router.push(`/detail/${item.goods.iid}/${item.goods.id}`)
              "
            >
              <div class="cart-top">
                <span style="font-weight: 600; font-size: 13px">{{
                  item.goods.shopName
                }}</span>
                <span style="font-size: 12px; color: #a1a4aa">免运费</span>
              </div>
              <div class="cart-content">
                <img :src="item.goods.show.img" />
                <div class="content">
                  <div class="title">{{ item.goods.title }}</div>
                  <div class="handler">
                    <span class="price">{{
                      item.goods.price | priceFilter
                    }}</span>
                    <div class="handler-btn">
                      <span @click="handleDecrement(item.id, index)">-</span>
                      <span style="background: #f8f8f9">{{ item.num }}</span>
                      <span @click="handleIncrement(item.id, index)">+</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </van-checkbox-group>
    </div>

    <van-empty description="购物车为空,赶紧去添加吧" v-else />
    <van-submit-bar
      v-if="carts.length > 0"
      :price="totalPrice"
      :style="styleVar"
    >
      <van-checkbox
        v-model="selectAll"
        @click="handleSelectAll"
        icon-size="14px"
        checked-color="#ff7500"
        >全选</van-checkbox
      >
      <!--  <template #button>
                <van-button>去结算</van-button>
              </template> -->
      <van-button
        slot="button"
        round
        size="small"
        style="width: 80px; height: 28px"
        color="linear-gradient(to right, #ff8e00, #ff7200)"
        v-if="!isEdit"
        @click="handleLink()"
        :disabled="!(ids.length > 0)"
        >去结算
        <van-badge :content="ids.length" color="#ffc712"></van-badge>
      </van-button>
      <van-button
        slot="button"
        round
        size="small"
        style="width: 80px; height: 28px"
        color="red"
        v-else
        @click="handleDelete(ids)"
        >删除
        <van-badge></van-badge>
      </van-button>
    </van-submit-bar>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { queryCart, queryGoodsDetail, editCart, deleteCart } from '@/api'
import NavBar from '../../components/nav-bar/nav-bar.vue'
import { Dialog } from 'vant'
export default {
  data() {
    return {
      carts: [], //购物车数据
      //单选按钮指的是ids
      ids: [],
      /* 全选按钮 */
      selectAll: false,
      isEdit: false
    }
  },
  computed: {
    //取出vuex中uid
    //辅助函数
    ...mapState({
      uid: (state) => state.userInfo.uid
    }),
    totalPrice() {
      return (
        this.carts
          .filter((item) => this.ids.indexOf(item.id) != -1)
          .reduce((pre, item) => pre + item.num * item.goods.price, 0) * 100
      )
    },
    styleVar() {
      return {
        '--inline-block': this.isEdit ? 'none' : 'inline-block'
      }
    }
  },
  components: { NavBar },
  mounted() {
    this.queryCart()
  },
  methods: {
    //查询购物车数据
    async queryCart() {
      const { data } = await queryCart({
        uid: this.uid
      })
      this.carts = data[0]
      this.carts.forEach(async (item) => {
        //item.goods.iid
        const { data } = await queryGoodsDetail(item.goods.iid)
        // =赋值 data中的数据更新了,但是页面的数据更新不到，这与Vue数据双向绑定实现原理有关，因为Vue2是基于Object.defineproperty实现的
        this.$set(item.goods, 'shopName', data.shopInfo.name)
      })
    },
    // 全选/反选
    handleSelectAll() {
      // 全选
      if (this.selectAll) this.ids = this.carts.map((item) => item.id)
      // 反选
      if (!this.selectAll) this.ids = []
    },
    //减少购物车数量
    async handleDecrement(id, index) {
      if (this.carts[index].num > 1) {
        this.carts[index].num--
        await editCart(id, this.carts[index].num)
      } else {
        //移除
        Dialog.confirm({
          title: '提示',
          message: '是否确认移除商品'
        }).then(() => {
          this.handleDelete([id])
        })
      }
    },
    //增加购物车数量
    async handleIncrement(id, index) {
      this.carts[index].num++
      await editCart(id, this.carts[index].num)
    },
    //删除购物车
    async handleDelete(id) {
      /* result 就是后端显示删除成功的提示 */
      const result = await deleteCart({ id: id })
      if (result) this.queryCart()
    },
    handleLink() {
      const info = this.carts
        .filter((item) => this.ids.indexOf(item.id) != -1)
        .map((item) => ({ gid: item.goods.id, num: item.num }))
      //params和query传参对象和数组，在刷新后数据丢失[object object]
      //第一种格式转换成JSON格式传参，第二种使用缓存localStorage和sessionStorage
      this.$router.push({
        path: '/order-detail',
        query: { info: JSON.stringify(info), id: JSON.stringify(this.ids) }
      })
    }
  },
  filters: {
    //价格过滤器
    priceFilter(price) {
      return '￥' + price.toFixed(2)
    }
  },
  watch: {
    //监听选中的购物车id数组
    ids(newValue) {
      this.selectAll = newValue.length === this.carts.length
    }
  }
}
</script>

<style lang="less" scoped>
.cart {
  background: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 110px;
  min-height: 100vh;
}

.cart-body {
  background: white;
  margin: -80px 15px 0 15px;
  border-radius: 10px;
}
.cart-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: white;
  border-radius: 10px;
  margin-bottom: 10px;
}
.cart-top {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.cart-content {
  display: flex;
  img {
    width: 80px;
    height: 80px;
    border-radius: 5px;
  }
  .content {
    flex: 1;
    padding-left: 10px;
  }
  .title {
    font-size: 13px;
    color: #090c19;
    text-overflow: ellipsis;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
}
.handler {
  display: flex;
  height: 50px;
  align-items: center;
  justify-content: space-between;
  .price {
    color: #ff3404;
    font-weight: 600;
  }
  .handler-btn span {
    display: inline-block;
    width: 25px;
    text-align: center;
  }
}
.van-submit-bar {
  bottom: 52px;
  .van-submit-bar__text span {
    display: var(--inline-block);
  }
}
</style>
